package com.hsapp.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.databinding.DataBindingUtil;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.hsapp.R;
import com.hsapp.databinding.ActivityBaseBinding;
import com.hsapp.listener.ToolbarIconClick;
import com.hsapp.listener.ViewClickListener;
import com.hsapp.model.LoadLayoutModel;
import com.hsapp.util.PreferencesUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;
import com.zyao89.view.zloading.ZLoadingDialog;
import com.zyao89.view.zloading.Z_TYPE;

import java.util.List;

/**
 * Created by nbzl on 2017/8/9.
 */
public class BaseActivity extends AppCompatActivity {
    protected ProgressDialog progressdialog;
    protected ActivityBaseBinding baseBinding;
    protected LocationManager locationManager;
    public Location location;
    public ZLoadingDialog dialog;
    protected LoadLayoutModel loadLayoutModel;
    public double Xlocation = 0, Ylocation = 0;
    public int REQUEST_CODE = 1;
    private Intent toIntent;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        baseBinding = DataBindingUtil.setContentView(this, R.layout.activity_base);
        setSupportActionBar(baseBinding.toolbar);
        progressdialog = new ProgressDialog(this);
        progressdialog.setCancelable(false);
        loadLayoutModel=new LoadLayoutModel(this,new LoadClick());
        initDialog();
        after();
    }

    private void initDialog(){
        dialog = new ZLoadingDialog(BaseActivity.this);
        dialog.setLoadingBuilder(Z_TYPE.STAR_LOADING)
                .setCancelable(false)
                .setLoadingColor(Color.BLACK)
                .setHintText("Loading...")
                .setHintTextSize(16)
                .setHintTextColor(Color.GRAY);
    }

    protected void after() {}
    public void reReques(){}

    protected void jumpToActivity(Class claz){
        toIntent=new Intent(BaseActivity.this,claz);
        startActivity(toIntent);
    }

    class LoadClick implements ViewClickListener {

        @Override
        public void reRequest(View view) {
            reReques();
        }
    }

    protected void showProgress(String msg) {
        progressdialog.setMessage(msg);
        progressdialog.show();
    }

    protected void AddContentView(View view) {
        baseBinding.content.removeAllViews();
        baseBinding.content.addView(view);
    }

    protected void handerBackToolar(String title) {
        //getmNavButtonView();
        baseBinding.toolbar.setTitle(title);
        //baseBinding.toolbar.setTitleMargin(-20,0,0,0);
        //baseBinding.toolbar.setSubtitle(title);
        setSupportActionBar(baseBinding.toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        Drawable drawable = baseBinding.toolbar.getNavigationIcon();//
        drawable.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
        getSupportActionBar().setHomeAsUpIndicator(drawable);
        baseBinding.toolbar.setTitleTextColor(Color.WHITE);
        baseBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }
    protected void handerIconToolar(String title,int icon,final ToolbarIconClick click){
        baseBinding.toolbar.setTitle(title);
        //baseBinding.toolbar.setTitleMargin(-20,0,0,0);
        //baseBinding.toolbar.setSubtitle(title);
        setSupportActionBar(baseBinding.toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        baseBinding.toolbar.setNavigationIcon(icon);//R.drawable.close
        //Drawable drawable = baseBinding.toolbar.getNavigationIcon();//
        //drawable.setColorFilter(getResources().getColor(R.color.white), PorterDuff.Mode.SRC_ATOP);
        //getSupportActionBar().setHomeAsUpIndicator(drawable);
        baseBinding.toolbar.setTitleTextColor(Color.WHITE);
        baseBinding.toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                click.iconClick();
            }
        });
    }


    public void setCount(String count) {
        if (count == null || count.equals("")) {
            baseBinding.count.setVisibility(View.GONE);
        } else {
            baseBinding.count.setVisibility(View.VISIBLE);
            baseBinding.count.setText(count + "条");
        }

    }

    protected void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    public void reLoad(View v) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Activity.RESULT_OK) {
            onResult(requestCode, data);
        }
    }

    public void onResult(int requestCode, Intent data) {
    }

    //////////////////////////////////// GPS定位//////////////////////////////////////////

    protected void openGpsTip() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                //已经禁止提示了
                Toast.makeText(BaseActivity.this, "您已禁止该权限，需要重新开启。", Toast.LENGTH_SHORT).show();
            } else {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, REQUEST_CODE);
            }

        } else {
            locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
            if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
                // Toast.makeText(this, "GPS正常", Toast.LENGTH_SHORT).show();
            } else {
                showDialog();
            }
            // 打开gps模块
            String provider = LocationManager.GPS_PROVIDER;

            location = locationManager.getLastKnownLocation(provider);
            // 初始化当前坐标信息\
            if (location != null) {
                Ylocation = location.getLatitude();//维度（2位）
                Xlocation = location.getLongitude();//经度（3位）
                Log.e("Mytext", Xlocation + "--" + Ylocation);

                PreferencesUtil.getInstance(BaseActivity.this).setLatitude(Ylocation + "");
                PreferencesUtil.getInstance(BaseActivity.this).setLongitude(Xlocation + "");
                // Toast.makeText(MainTabActivity.this,
                // "Xlocation="+Xlocation+"---Ylocation="+Ylocation,
                // Toast.LENGTH_LONG).show();
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 200, locationListener);

        }


    }

    protected void requestGps() {
        AndPermission.with(this)
                .requestCode(100)
                .permission(Permission.LOCATION,Permission.CAMERA)
                .rationale(new RationaleListener() {

                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        AndPermission.rationaleDialog(BaseActivity.this, rationale).show();
                    }
                })
                .callback(listener)
                .start();
    }


    private boolean checkGPSIsOpen() {
        boolean isOpen;
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        isOpen = locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
        return isOpen;
    }

    private PermissionListener listener = new PermissionListener() {

        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            if (requestCode == 100) {

                if(AndPermission.hasPermission(BaseActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)){
                    if(checkGPSIsOpen()){
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10 * 1000, 200, locationListener);
                    }else{
                        showDialog();
                    }
                }else{
                }

                if(AndPermission.hasPermission(BaseActivity.this,Manifest.permission.CAMERA)){
                    Log.e("Mytext","获取相机权限");
                }else{
                    Log.e("Mytext","获取相机权限失败");
                }
                /*locationManager = (LocationManager) BaseActivity.this.getSystemService(Context.LOCATION_SERVICE);
                //LocationProvider gpsProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
                if (ActivityCompat.checkSelfPermission(BaseActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(BaseActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(BaseActivity.this, "无法定位，请打开定位服务", Toast.LENGTH_SHORT).show();
                    Intent i = new Intent();
                    i.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    startActivity(i);
                    return;
                }*/
                //locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2 * 1000, 100, locationListener);
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            if(requestCode==200){
                Log.e("Mytext","权限获取失败");
            }

        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //用户同意授权
                    //callPhone();
                } else {
                    //用户拒绝授权
                }
                break;
        }
    }

    private void showDialog() {
        // TODO Auto-generated method stub
        AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
        builder.setTitle("设置").setMessage("请开启Gps！");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                // startActivityForResult(intent,0); //此为设置完成后返回到获取界面
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                BaseActivity.this.startActivity(intent);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    private LocationListener locationListener = new LocationListener() {

        /**
         * GPS状态变化时触发
         */
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub
            Log.e("Mytext", "onStatusChanged..." + provider);

        }

        /**
         * GPS开启时触发
         */
        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
            Log.e("Mytext", "onProviderEnabled..." + provider);

        }

        /**
         * GPS禁用时触发
         */
        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
            Log.e("Mytext", "onProviderDisabled..." + provider);

        }

        /**
         * 位置信息变化时触发
         */
        @Override
        public void onLocationChanged(Location location) {
            Ylocation = location.getLatitude();
            Xlocation = location.getLongitude();//经度
            //PreferencesUtil.getInstance(BaseActivity.this).setLatitude(Ylocation + "");
            //PreferencesUtil.getInstance(BaseActivity.this).setLongitude(Xlocation + "");
            //Static.showToast(BaseActivity.this,"Xlocation-->" + Xlocation + "  Ylocation-->" + Ylocation);
            Log.e("Mytext", "Xlocation-->" + Xlocation + "  Ylocation-->" + Ylocation);
        }

    };
}
